package com.jiang.mall.mallproduct.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiang.common.constant.ProductConstant;
import com.jiang.common.to.SkuReductionTo;
import com.jiang.common.to.SpuBoundTo;
import com.jiang.common.to.es.SkuEsModel;
import com.jiang.common.utils.PageUtils;
import com.jiang.common.utils.Query;
import com.jiang.common.utils.R;
import com.jiang.mall.mallproduct.product.dao.SpuInfoDao;
import com.jiang.mall.mallproduct.product.entity.*;
import com.jiang.mall.mallproduct.product.feign.CouponFeignService;
import com.jiang.mall.mallproduct.product.feign.SearchFeignService;
import com.jiang.mall.mallproduct.product.feign.WareFeignService;
import com.jiang.mall.mallproduct.product.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2.保存spu的描述图片 pms_spu_info_desc
        List<String> decripts = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decripts));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3.保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());

            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);

        //保存spu的积分信息 sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        //5.保存当前spu对应的所有sku信息
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images img : item.getImages()) {
                    if (img.getDefaultImg() == 1) {
                        defaultImg = img.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //5.1)、sku的基本信息 pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> !StringUtils.isEmpty(entity.getImgUrl())).collect(Collectors.toList());
                //5.2)、sku的图片信息 pms_sku_images
                skuImagesService.saveBatch(imagesEntities);
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                //5.3)、sku的销售属性信息 pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //5.4)、sku的优惠、满减等信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) == 1) {
                    R r1 = couponFeignService.saveskuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !brandId.equals("0")) {
            queryWrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !catelogId.equals("0")) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //组装需要的数据

        //1.查出当前spuId对应的所有sku信息，品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);
        Map<Long, Boolean> data = null;
        try {
            data = (Map<Long, Boolean>) wareFeignService.getSkuHasStock(skuInfoEntities.stream().map(i -> i.getSkuId()).collect(Collectors.toList())).get("data");
        } catch (Exception e) {
            log.error("远程调用库存查询失败,原因：", e);
        }

        //TODO 4.查询当前sku所有可以被检索的规格属性
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = productAttrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<String> valuesSearch = productAttrValueEntities.stream().map(ProductAttrValueEntity::getAttrValue).collect(Collectors.toList());
        List<AttrEntity> attrEntities = attrIds.stream().map(attrId -> attrService.getById(attrId)).filter(attrId -> attrService.getById(attrId).getSearchType() == 1).collect(Collectors.toList());
        List<SkuEsModel.Attrs> skuEsModelAttrss = attrEntities.stream().map(attr -> {
            SkuEsModel.Attrs skuEsModelAttrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(attr, skuEsModelAttrs);
            String[] split = attr.getValueSelect().split(";");
            if (split.length > 1) { //属性值多选
                for (String s : split) {
                    if (valuesSearch.contains(s)) {
                        skuEsModelAttrs.setAttrValue(s);
                    }
                }
            } else { //属性值单选
                skuEsModelAttrs.setAttrValue(attr.getValueSelect());
            }
            return skuEsModelAttrs;
        }).collect(Collectors.toList());
        //2.封装每个sku的信息
        Map<Long, Boolean> finalData = data;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(skuInfo -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            //字段名能对上的直接拷贝
            BeanUtils.copyProperties(skuInfo, skuEsModel);
            //字段名对不上的挨个手动赋值
            skuEsModel.setSkuPrice(skuInfo.getPrice());
            skuEsModel.setSkuImg(skuInfo.getSkuDefaultImg());
            //TODO 1.发送远程调用，查询是否有库存
            //记一大坑 远程调用传过来的都是Json字符串类型的，key都是字符串！！！
            if (finalData != null && finalData.get(skuInfo.getSkuId().toString())) {
//                Long ss = skuInfo.getSkuId();
//                boolean isContains = false;
//                for(int i = 0; i < finalData.size(); i ++) {
//                    Long temp = finalData.get(i);
//                    if(temp.equals(ss))
//                        isContains = true;
//                }
//                for(Long sss:finalData) {
//                    if(sss.equals(ss)) {
//                        isContains = true;
//                    }
//                }
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(false);
                log.info("库存不足，上架失败，skuId为{}", skuInfo.getSkuId());
            }

            //TODO 2.热度评分设置为 0
            skuEsModel.setHotScore(0L);

            //TODO 3.品牌和分类的名字等信息
            BrandEntity brand = brandService.getById(skuInfo.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());
            skuEsModel.setCatalogName(categoryService.getById(skuInfo.getCatalogId()).getName());
            //设置检索属性
            skuEsModel.setAttrs(skuEsModelAttrss);

            return skuEsModel;
        }).collect(Collectors.toList());
        //TODO 5.将数据发送给es进行保存
        R r = searchFeignService.productStatusUp(skuEsModels);
        if (r.getCode() == 0) {
            //TODO 6.修改当前spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {

        }
    }

}
